package com.freedom.util.sys;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextHolder implements ApplicationContextAware{

	/**  
     * 以静态变量保存ApplicationContext,可在任意代码中取出ApplicaitonContext.  
     */    
   private static ApplicationContext context; 
   public static ApplicationContext getApplicationContext() {    
       return context;
   }
	@Override
	public void setApplicationContext(ApplicationContext context)
			throws BeansException {
		SpringContextHolder.context =context;
	}
	
	/**  
     * 第一种方式，从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.  
     */    
    @SuppressWarnings("unchecked")
	public static <T> T getBean(String name) {  
        return (T) context.getBean(name);    
    }
    
    /**
     * 第二种方式，类反射方式获取
     * @param t
     * @return
     */
    @SuppressWarnings("unchecked")
	public static <T> T getBean(Class<?> t){
    	return (T) context.getBean(t);
    }
}
